from Player import Player
from TicTacToeGame import TicTacToe

class GameController:
	def __init__(self, player1, player2):
		self.player1 = player1
		self.player2 = player2
		#Now we have everything we need to make a game!
	
	def newGame(self):
		self.game = TicTacToe()
		
		player = 1
		results = None
		lastMove = None
		
		self.drawBoard()
		
		while results == None:
			if player:
				self.player1.messageToPlayer("It's your move")
				if self.player2:
					self.player2.messageToPlayer("Waiting on " + self.player1.playerName)
				
				lastMove = self.player1.move(lastMove)
				results = self.game.placeMarker(1, lastMove)
				player -= 1
			else:
				if self.player2:
					self.player2.messageToPlayer("It's your move")
					self.player1.messageToPlayer("Waiting on " + self.player2.playerName)
					
					lastMove = self.player2.move(lastMove)
				else:
					lastMove = self.game.getComputerMove()

				results = self.game.placeMarker(2, lastMove)
				player += 1
			
			if self.player2 or player:
				self.drawBoard()
		
		self.gameOver(results)
		self.drawBoard()
	
	def gameOver(self, results):
		if results == 0:
			self.player1.messageToPlayer("It's a draw, everybody loses")
			if self.player2:
				self.player2.messageToPlayer("It's a draw, everybody loses")
			
		elif results == 1:
			self.player1.messageToPlayer("You win!")
			if self.player2:
				self.player2.messageToPlayer("You lose!")
			
		elif results == 2:
			self.player1.messageToPlayer("You lose!")
			if self.player2:
				self.player2.messageToPlayer("You win!")
	
	def drawBoard(self):
		boardList = []
		for marker in self.game.board:
			if marker:
				if marker == 1:
					boardList.append('X')
				else:
					boardList.append('O')
			else:
				boardList.append(" ")
			
		board = """
			  %s  |  %s  |  %s
			--------------------
			  %s  |  %s  |  %s  
			--------------------
			  %s  |  %s  |  %s""" % (boardList[0], boardList[1],  boardList[2], boardList[3], boardList[4], boardList[5], boardList[6], boardList[7], boardList[8])
		print board
